<?php

namespace app\admin\logic;

use app\admin\model\article\Article;
use app\admin\model\finance\UserCommissionWithdraw;
use app\admin\model\order\Order;
use app\admin\model\user\UserMember;
use app\basic\BaseLogic;
use think\facade\Db;

class DashboardLogic extends BaseLogic
{
    /**
     * 获取仪表盘统计数据
     */
    public function getDashboardStatistics()
    {
        // 获取今天和昨天的日期
        $today = date('Y-m-d');
        $yesterday = date('Y-m-d', strtotime('-1 day'));

        // 会员统计
        $totalMembers = UserMember::where('status', 1)->count();
        $todayMembers = UserMember::where('status', 1)
            ->whereDay('create_time', $today)
            ->count();
        $yesterdayMembers = UserMember::where('status', 1)
            ->whereDay('create_time', $yesterday)
            ->count();

        // 文档统计
        $totalDocuments = Article::where('status', 1)->count();
        $todayDocuments = Article::where('status', 1)
            ->whereDay('create_time', $today)
            ->count();
        $yesterdayDocuments = Article::where('status', 1)
            ->whereDay('create_time', $yesterday)
            ->count();

        // 订单统计
        $todayOrders = Order::where('pay_status', 20)
            ->whereDay('pay_time', $today)
            ->count();
        $yesterdayOrders = Order::where('pay_status', 20)
            ->whereDay('pay_time', $yesterday)
            ->count();

        // 收入统计
        $totalIncome = Order::where('pay_status', 20)->sum('pay_price');
        $todayIncome = Order::where('pay_status', 20)
            ->whereDay('pay_time', $today)
            ->sum('pay_price');
        $yesterdayIncome = Order::where('pay_status', 20)
            ->whereDay('pay_time', $yesterday)
            ->sum('pay_price');

        // 计算环比增长率
        $memberRate = $this->calculateGrowthRate($todayMembers, $yesterdayMembers);
        $documentRate = $this->calculateGrowthRate($todayDocuments, $yesterdayDocuments);
        $orderRate = $this->calculateGrowthRate($todayOrders, $yesterdayOrders);
        $incomeRate = $this->calculateGrowthRate($todayIncome, $yesterdayIncome);

        return [
            'total_members' => $totalMembers,
            'total_documents' => $totalDocuments,
            'today_orders' => $todayOrders,
            'total_income' => number_format($totalIncome, 2),
            'member_rate' => $memberRate,
            'document_rate' => $documentRate,
            'order_rate' => $orderRate,
            'income_rate' => $incomeRate
        ];
    }

    /**
     * 计算环比增长率
     */
    private function calculateGrowthRate($today, $yesterday)
    {
        if($yesterday == 0) {
            return $today > 0 ? '100%' : '0%';
        }
        $rate = ($today - $yesterday) / $yesterday * 100;
        return sprintf('%.2f%%', $rate);
    }

    /**
     * 获取财务统计数据
     */
    public function getFinanceStatistics()
    {

        // 累计充值金额
        $totalRecharge = $this->getTotalRecharge();

        // 累计提现金额
        $totalWithdraw = $this->getTotalWithdraw();

        // 用户剩余充值金额
        $balanceAmount = $this->getUserBalanceAmount();

        // 用户待提现金额
        $pendingWithdraw = $this->getPendingWithdrawAmount();

        return [
            'total_recharge' => number_format($totalRecharge, 2),
            'total_withdraw' => number_format($totalWithdraw, 2),
            'balance_amount' => number_format($balanceAmount, 2),
            'pending_withdraw' => number_format($pendingWithdraw, 2),
        ];
    }

    /**
     * 获取累计充值金额
     */
    private function getTotalRecharge()
    {
        return Db::name("money_recharge_order")->where('pay_status','1')->sum('money');
    }

    /**
     * 获取累计提现金额
     */
    private function getTotalWithdraw()
    {
        return UserCommissionWithdraw::where("status",'1')->sum('money');
    }

    /**
     * 获取用户剩余充值金额
     */
    private function getUserBalanceAmount()
    {
        return \app\admin\model\user\UserMember::sum('money');
    }

    /**
     * 获取用户待提现金额
     */
    private function getPendingWithdrawAmount()
    {
         return \app\admin\model\user\UserMember::sum('commission_money');
    }

    /**
     * 获取指定日期的充值金额
     */
    private function getDailyRecharge($date)
    {
        return \app\admin\model\finance\UserMoneyLog::where([
            ['type', '=', 1], // 充值类型
            ['status', '=', 1] // 成功状态
        ])->whereDay('create_time', $date)
          ->sum('money');
    }

    /**
     * 获取指定日期的提现金额
     */
    private function getDailyWithdraw($date)
    {
        return \app\admin\model\finance\UserMoneyLog::where([
            ['type', '=', 2], // 提现类型
            ['status', '=', 1] // 成功状态
        ])->whereDay('create_time', $date)
          ->sum('money');
    }

    /**
     * 获取待审核提现统计
     */
    public function getWithdrawPendingStats()
    {
        // 查询待审核提现记录
        $query = UserCommissionWithdraw::where("status","0");

        // 统计总的待审核数据
        $pendingCount = $query->count();

        return [
            'pending_count' => $pendingCount,
        ];
    }

    /**
     * 获取消费统计数据
     */
    public function getConsumeStatistics($type = 'week')
    {
        switch ($type) {
            case 'week':
                return $this->getWeekStatistics();
            case 'month':
                return $this->getMonthStatistics();
            case 'year':
                return $this->getYearStatistics();
            default:
                return $this->getWeekStatistics();
        }
    }

    /**
     * 获取本周统计
     */
    private function getWeekStatistics()
    {
        $dates = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        $recharge = [];
        $consume = [];

        // 获取本周的开始日期
        $weekStart = date('Y-m-d', strtotime('this week monday'));

        // 统计每天的数据
        for ($i = 0; $i < 7; $i++) {
            $date = date('Y-m-d', strtotime($weekStart . "+$i day"));

            // 统计充值
//            $recharge[] = Db::name("money_recharge_order")->where("pay_status","1")->whereDay('create_time', $date)->sum('money');

            // 统计消费
            $consume[] = \app\admin\model\order\Order::where([
                ['pay_status', '=', 20]  // 支付成功
            ])->whereDay('pay_time', $date)->sum('pay_price');
        }

        return [
            'dates' => $dates,
            'recharge' => $recharge,
            'consume' => $consume
        ];
    }

    /**
     * 获取本月统计
     */
    private function getMonthStatistics()
    {
        $days = date('t'); // 获取当月天数
        $dates = array_map(function($i) { return $i . '日'; }, range(1, $days));
        $recharge = [];
        $consume = [];

        // 获取本月的开始日期
        $monthStart = date('Y-m-01');

        // 统计每天的数据
        for ($i = 0; $i < $days; $i++) {
            $date = date('Y-m-d', strtotime($monthStart . "+$i day"));


            // 统计充值
//           $recharge[] = Db::name("money_recharge_order")->where("pay_status","1")->whereDay('create_time', $date)->sum('money');

            // 统计消费
            $consume[] = \app\admin\model\order\Order::where([
                ['pay_status', '=', 20]  // 支付成功
            ])->whereDay('pay_time', $date)->sum('pay_price');
        }

        return [
            'dates' => $dates,
            'recharge' => $recharge,
            'consume' => $consume
        ];
    }

    /**
     * 获取本年统计
     */
    private function getYearStatistics()
    {
        $dates = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
        $recharge = [];
        $consume = [];

        // 获取本年的开始日期
        $yearStart = date('Y-01-01');

        // 统计每月的数据
        for ($i = 0; $i < 12; $i++) {
            $startDate = date('Y-m-d', strtotime($yearStart . "+$i month"));
            $endDate = date('Y-m-d', strtotime($yearStart . "+".($i+1)." month -1 day"));

//            // 统计充值
//            $recharge[] = Db::name("money_recharge_order")
//                ->where("pay_status","1")->whereBetween('create_time', [strtotime($startDate), strtotime($endDate)])
//                ->sum('money');
            // 统计消费
            $consume[] = \app\admin\model\order\Order::where([
                ['pay_status', '=', 20]  // 支付成功
            ])->whereBetween('pay_time', [strtotime($startDate), strtotime($endDate)])->sum('pay_price');
        }
        
        return [
            'dates' => $dates,
            'recharge' => $recharge,
            'consume' => $consume
        ];
    }

}